package org.testis.guiappsmodule.services;

import org.testis.data.AtofModuleConstants;
import org.testis.guiappsmodule.data.GuiAppsModuleDataObject;
import org.testis.logging.AtofLogLevel;
import org.testis.logging.LogSenderService;
import org.testis.utils.TerminalApplicationExecutor;
import org.testis.utils.UuidGenerator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


/**
 *
 * @author nurhat
 */
public class WindowsExecuteAction implements OsExecuteAction
{

    public boolean executeGuiScript(GuiAppsModuleDataObject dataObj)
    {
        boolean result = false;
        String uuid = UuidGenerator.generateMsgId();
        String fileName = AtofModuleConstants.ATOF_CLIENT_HOME + "/" + uuid +
            ".py";
        File file = new File(fileName);
        BufferedWriter output = null;
        try {
            output = new BufferedWriter(new FileWriter(file));
            output.write(dataObj.getScript());
            output.close();
            if (dataObj.getParameters() == null) {
                dataObj.setParameters("");
            }
            TerminalApplicationExecutor executor =
                new TerminalApplicationExecutor("python \"" + fileName + "\"",
                                                dataObj.getParameters());
            Integer exitVal = executor.runExec();
            dataObj.setExitCode(exitVal.toString());
            dataObj.setErrorString(executor.getErrorString());
            dataObj.setOutputString(executor.getOutputString());
            LogSenderService.putMessageOnQueue(
                "GuiApps WindowsExecuteAction",
                AtofLogLevel.INFO,
                "GuiApp   executed. " + System.getProperties().
                getProperty(
                "line.separator") + "Output:" + dataObj.getOutputString() + System.getProperties().
                getProperty(
                "line.separator") + "Error Output:" + dataObj.getErrorString() + System.getProperties().
                getProperty(
                "line.separator") + "Exit Code:" + dataObj.getExitCode(),
                dataObj.getMessageId());
            result = true;

        } catch (IOException ex) {
            throw new GuiAppsException(GuiAppsExceptionType.IO_EXCEPTION,
                                       "IOException occured(WindowsExecuteAction)." +
                                       ex.getMessage());
        } catch (InterruptedException ex) {
            throw new GuiAppsException(
                GuiAppsExceptionType.INTERRUPTED_EXCEPTION,
                "Interrupted exception occured(WindowsExecuteAction)." + ex.
                getMessage());
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
        return result;
    }
}
